<template>
  <div class="message-page">
    <a-card :bordered="false">
      <div class="message-header">
        <h2>我的消息</h2>
        <a-button 
          type="link" 
          :loading="readAllLoading"
          @click="handleReadAll"
        >
          全部标记为已读
        </a-button>
      </div>
      
      <a-list
        class="message-list"
        :loading="loading"
        :data-source="messages"
        :locale="{emptyText: '暂无消息'}"
      >
        <a-list-item 
          slot="renderItem" 
          slot-scope="item" 
          :class="{'unread': item.isRead === '1'}"
        >
          <a-list-item-meta>
            <template slot="avatar">
              <a-avatar :src="item.avatar">
                <template v-if="!item.avatar">
                  <a-icon :type="getMessageIcon(item.type)" />
                </template>
              </a-avatar>
            </template>
            <div slot="title" class="message-title">
              <span>{{ getMessageTitle(item.type) }}</span>
              <span class="message-time">{{ item.createTime }}</span>
            </div>
            <div slot="description">
              <div class="message-content">
                {{ item.content }}
              </div>
              <div v-if="item.isRead === '1'" class="message-action">
                <a-button 
                  type="link" 
                  size="small"
                  :loading="item.markingRead"
                  @click.stop="handleMarkAsRead(item)"
                >
                  标记已读
                </a-button>
              </div>
            </div>
          </a-list-item-meta>
        </a-list-item>
      </a-list>
    </a-card>
  </div>
</template>

<script>
import { message } from '@/api/message'
import { EventBus } from '@/utils/eventBus'

export default {
  name: 'Message',
  data() {
    return {
      loading: false,
      readAllLoading: false,
      messages: [],
      userId: localStorage.getItem('loginId') || ''
    }
  },
  created() {
    this.fetchMessages()
  },
  methods: {
    async fetchMessages() {
      if (!this.userId) return
      
      this.loading = true
      try {
        const res = await message.getList({
          userId: this.userId
        })
        if (res.code === 200) {
          // 为每条消息添加markingRead状态
          this.messages = res.content.map(msg => ({
            ...msg,
            markingRead: false
          }))
        }
      } catch (error) {
        this.$message.error('获取消息失败')
      } finally {
        this.loading = false
      }
    },
    
    async handleReadAll() {
      if (!this.userId) return
      
      this.readAllLoading = true
      try {
        const res = await message.readAll({
          userId: this.userId
        })
        if (res.code === 200) {
          this.$message.success('已全部标记为已读')
          // 更新所有消息为已读状态
          this.messages = this.messages.map(msg => ({
            ...msg,
            isRead: '0',
            markingRead: false
          }))
          // 获取最新的未读消息数量
          const countRes = await message.getUnreadCount({
            userId: this.userId
          })
          if (countRes.code === 200) {
            EventBus.$emit('updateUnreadCount', countRes.content.count)
          }
          // 重新获取消息列表
          await this.fetchMessages()
        }
      } catch (error) {
        this.$message.error('操作失败')
      } finally {
        this.readAllLoading = false
      }
    },
    
    async handleMarkAsRead(item) {
      if (!item || item.isRead === '0') return
      
      // 设置loading状态
      this.$set(item, 'markingRead', true)
      
      try {
        const res = await message.read({
          messageId: item.id,
          userId: this.userId
        })
        if (res.code === 200) {
          this.$set(item, 'isRead', '0')
          this.$message.success('已标记为已读')
          // 获取最新的未读消息数量
          const countRes = await message.getUnreadCount({
            userId: this.userId
          })
          if (countRes.code === 200) {
            EventBus.$emit('updateUnreadCount', countRes.content.count)
          }
          // 重新获取消息列表
          await this.fetchMessages()
        }
      } catch (error) {
        console.error('标记已读失败:', error)
        this.$message.error('标记已读失败')
      } finally {
        this.$set(item, 'markingRead', false)
      }
    },
    
    // 根据消息类型获取图标
    getMessageIcon(type) {
      const iconMap = {
        '1': 'heart',    // 点赞消息
        '2': 'message'   // 评论消息
      }
      return iconMap[type] || 'notification'
    },
    
    // 根据消息类型获取标题
    getMessageTitle(type) {
      const titleMap = {
        '1': '收到点赞',
        '2': '收到评论'
      }
      return titleMap[type] || '系统通知'
    }
  }
}
</script>

<style scoped>
.message-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.message-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.message-list {
  background: #fff;
}

.message-list .ant-list-item {
  padding: 16px 24px;
  transition: background-color 0.3s;
}

.message-list .ant-list-item:hover {
  background-color: #f5f5f5;
}

.message-list .unread {
  background-color: #e6f7ff;
}

.message-list .unread:hover {
  background-color: #bae7ff;
}

.message-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-time {
  font-size: 12px;
  color: #8c8c8c;
}

.message-content {
  color: #595959;
}

.message-action {
  margin-top: 8px;
}

.message-action .ant-btn {
  padding: 0;
  height: auto;
  line-height: 1.5;
}

.ant-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #1e80ff;
}

.ant-avatar .anticon {
  font-size: 18px;
}
</style> 